package com.qf.security;

import com.qf.utils.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class QfLogoutHandler implements LogoutHandler {
    RedisTemplate redisTemplate;

    public QfLogoutHandler(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        //注销登录时的业务
        //redisTemplate-->从redis中删除记录的用户信息
        //从redis中删除记录的用户信息
        //从请求request中请求头获得token携带的uuid
        try {
            String uuid = request.getHeader("token");
            //验证
            Object token = redisTemplate.opsForValue().get(uuid);
            if (token != null && token instanceof String) {
                String jwt = (String) token;
                //TokenTools工具类调用验证方法
                String username = TokenTools.getName(jwt);
                redisTemplate.delete(RedisKey.LOGIN_ADMIN + uuid);

                ResponseUtils.response(response, ResultMsg.SUCCESS("注销成功"));
//                return;
            }
            //ResponseUtils.response(response, ResultMsg.success("注销失败"));
        }catch (Exception e){
            //e.printStackTrace();
            throw new RuntimeException("注销失败");
        }
    }
}
